package com.nuaa.controller.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/upload")
public class UploadController {
	@RequestMapping("/over/{status}")
	public String uploadOver(@PathVariable("status") Integer status) {
		if(status==0) return "error";
		return "success";
	}
	@RequestMapping("/uploadImg.do")
	public void uploadImg(MultipartFile file) {
		System.out.println(file.getOriginalFilename()); 
		try {
			InputStream input = file.getInputStream();
			FileOutputStream output = new FileOutputStream(new File("F:\\workspace\\"+file.getOriginalFilename()));
			byte [] ch = new byte[1024];
			int len = 0;
			while((len=input.read(ch))>0) {
				output.write(ch, 0, len);
			}
			output.flush();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/uploadImg2.do")
	public void uploadImag2(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		System.out.println(request.getContextPath());
		String serverPath = request.getSession().getServletContext().getRealPath("/");
		File saveDir = new File(serverPath+"upload");
		if(!saveDir.exists()) saveDir.mkdir();
		try {
			String uuid = UUID.randomUUID().toString();
			String originalFilename = file.getOriginalFilename();
			int index = originalFilename.lastIndexOf(".");
			String filename = uuid.concat(originalFilename.substring(index));
			file.transferTo(new File(saveDir.toString()+"/"+filename));
			request.getRequestDispatcher("/upload/over/1").forward(request, response);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
